package wx.display
{
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	/**
	 * 
	 * @author wujianqi
	 * 
	 * Modified from binghe/9ria.com
	 * 九宫格
	 * 
	 */	
	public class ScaleBitmapSprite extends Sprite
	{
		
		private var _width:Number;       
		private var _height:Number; 
		private var _bitmap:Bitmap;
		private var _scale9Grid:Rectangle;
		
		public function ScaleBitmapSprite(bmp:Bitmap=null,s9g:Rectangle=null,nw:Object=null,nh:Object=null)
		{
			super();			
			if(bmp!=null && s9g!=null && nw!=null && nh!=null){
				_bitmap = bmp;
				_scale9Grid = s9g;
				_width = nw as Number;
				_height = nh as Number;
				measure();
			}
		}
		
		public function set bitmap(bmp:Bitmap):void{
			_bitmap = bmp;
		}
			
		override public function set scale9Grid(rect:Rectangle):void{
			_scale9Grid = rect;
		}
		override public function get scale9Grid():Rectangle {
			return _scale9Grid;      
		} 
		
		override public function get width():Number {
			return _width;      
		}       
		override public function set width(value:Number):void{           
			if(_width != value){
				_width = value;
				measure();
			}			       
		}  
		
		override public function get height():Number {
			return _height;       
		}       
		override public function set height(value:Number):void{
			if(_height != value){
				_height = value;
				measure();
			}
		} 
		
		private function measure():void
		{
			if(isNaN(_width) || isNaN(_height)) return;

			var rows:Vector.<Number> = new <Number>[0,_scale9Grid.top,_scale9Grid.bottom,_bitmap.height];
			var cols:Vector.<Number> = new <Number>[0,_scale9Grid.left,_scale9Grid.right,_bitmap.width];
			
			var dRows:Vector.<Number> = new <Number>[0, _scale9Grid.top, _height - (_bitmap.height - _scale9Grid.bottom), _height];
			var dCols:Vector.<Number> = new <Number>[0, _scale9Grid.left, _width - (_bitmap.width - _scale9Grid.right), _width];
			
			var origin:Rectangle= new Rectangle();
			var draw:Rectangle = new Rectangle;
			var mat:Matrix = new Matrix();
			
			graphics.clear();
			for (var cx : int = 0; cx < 3; cx++)
			{
				for (var cy : int = 0; cy < 3; cy++)
				{
					origin.x = cols[cx];
					origin.y = rows[cy];
					origin.width = cols[cx + 1] - cols[cx];
					origin.height = rows[cy + 1] - rows[cy];
					
					draw.x = dCols[cx];
					draw.y = dRows[cy];
					draw.width = dCols[cx + 1] - dCols[cx];
					draw.height = dRows[cy + 1] - dRows[cy];
					
					mat.identity();
					mat.a = draw.width / origin.width;
					mat.d = draw.height / origin.height;
					mat.tx = draw.x - origin.x * mat.a;
					mat.ty = draw.y - origin.y * mat.d;
					
					graphics.beginBitmapFill(_bitmap.bitmapData,mat,false,true);
					graphics.drawRect(draw.x,draw.y,draw.width,draw.height);
				}
			}
			graphics.endFill();
		}	
		
		
		
	}
}